package multimedia;

import gov.nist.core.StringTokenizer;

import java.rmi.RemoteException;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import midlet.VadeMecumMIDlet;
import ui.QueryResultForm;
import ui.VadeMecumList;
import util.VadeMecumConstants;
import webservice.VadeMecumMultimediaServicePortType_Stub;

public class QueryFilesThread implements Runnable, CommandListener {

	private VadeMecumMIDlet midlet;
	
	private Displayable previous;
	
	private VadeMecumMultimediaServicePortType_Stub stub;
	
	public QueryFilesThread(VadeMecumMIDlet midlet, Displayable previous) {
		this.midlet = midlet;
		this.previous = previous;
	}
	
	public void run() {
		System.out.println("pegando arquivos...");
		stub = new VadeMecumMultimediaServicePortType_Stub();
		try {
			String result = stub.queryAll();
			System.out.println(result);
//			QueryResultForm form;
			VadeMecumList resultList;
			if (result != null) {
				Vector results = new Vector();
				StringTokenizer st = new StringTokenizer(result, '#');
				while (st.hasMoreChars()) {	
					String token = st.nextToken();
					results.addElement(token.substring(0, token.length() - 1));
				}
				String[] options = new String[results.size() + 1];
				for (int i = 0; i < results.size(); i++) {
					options[i] = (String) results.elementAt(i);
				}
				options[results.size()] = VadeMecumConstants.BACK;
				resultList = new VadeMecumList("Query results", List.IMPLICIT, options, null);//new VadeMecumList(this.midlet, result);
				resultList.setCommandListener(this);
				midlet.display.setCurrent(resultList);
			} else {
				QueryResultForm form = new QueryResultForm(this.midlet, "No files found");
				form.setCommandListener(this.midlet);
				midlet.display.setCurrent(form);
			}
//			previous.repaint();			
		} catch (RemoteException re) {
//			if ("SAXParseException in response from server".equals(re.getMessage().trim())){
////				previous.repaint();
//				midlet.display.setCurrent(alert, previous);
//			} else {				
				midlet.error(re);
//			}
		}
	}

	public void commandAction(Command cmd, Displayable d) {
		if (cmd == List.SELECT_COMMAND) {
			VadeMecumList current = (VadeMecumList) this.midlet.display.getCurrent();
			String selectedOption = current.getString(current.getSelectedIndex());
			if (VadeMecumConstants.BACK.equalsIgnoreCase(selectedOption)) {
				this.midlet.display.setCurrent(previous);
			} else {
				String st = selectedOption.substring(0, selectedOption.indexOf(" "));
				Thread getFileThread = new Thread(new GetFileThread(this.midlet, this.previous, new Integer(Integer.parseInt(st))));
				getFileThread.start();
			}
		}
	}	

}
